from django.apps.registry import Apps
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest
# Create your views here.
from django.shortcuts import render
from django.views.decorators.http import require_GET, require_POST
from django.views.generic import FormView

from IM.forms import UserForm, ImageForm
import uuid
from IM.models import AuthUser


def auth_user_pass(request):
    username = request.GET["username"]
    password = request.GET['password']
    user = authenticate(request, username=username, password=password)
    if user:
        user.token = uuid.uuid4().hex
        user.save()
        return JsonResponse({"errcode": 0, "token": user.token})
    else:
        return JsonResponse({"errcode": 1, "errmsg": "invalid user name or password"})


@require_POST
def auth_user_token(request):
    username = request.GET['username']
    token = request.GET['token']

    try:
        user = AuthUser.objects.get(username=username, token=token)
        user.save()
        return JsonResponse({"errcode": 0})
    except:
        return JsonResponse({"errcode": 1})


def register(request):
    if request.method == "GET":
        return render(request, "register.html", {"form": UserForm()})
    else:
        user_form = UserForm(request.POST, request.FILES)
        if user_form.is_valid():
            try:
                # if not user_form.cleaned_data['username']:
                #     user_form.add_error("username", "You must set username")
                #     return render(request, "register.html", {"error_form": user_form})

                u = AuthUser()
                u.avatar = user_form.cleaned_data['avatar']
                u.username = user_form.cleaned_data["username"]
                u.password = make_password(user_form.cleaned_data["password"])
                u.email = user_form.cleaned_data["email"]
                u.save()
                return HttpResponse("register success")
            except Exception as e:
                return HttpResponse(str(e))
        else:
            return render(request, "register.html", {"error_form": user_form})


@require_GET
def get_user(request, username):
    try:
        user = AuthUser.objects.get(username=username)
        return render(request, "user.html", {"user": user})
    except:
        return HttpResponseBadRequest()


# @require_POST
def get_users(request):
    return JsonResponse([u.to_json() for u in AuthUser.objects.all()], safe=False)


def upload_file(request):
    print(request.FILES)
    return HttpResponse()


def logout_user(request):
    logout(request)
    return JsonResponse({"errcode": 0})


def show_user(request, username):
    try:
        user = AuthUser.objects.get(username=username)
        usrForm = UserForm(initial={
            "avatar": user.avatar,
            "username": user.username,
            "password": user.password,
            "email": user.email
        })
        return render(request, "user.html", {"form": usrForm, "user": user})
    except:
        return HttpResponseBadRequest()


class ImageView(FormView):
    form_class = ImageForm
    template_name = "upload.html"

    def form_valid(self, form):
        form.instance.save()
        return HttpResponse(form.instance.image.url)